/**
 * @author 徐楠
 * @date 2021/12/4 21:07
 * @version 1.0
 */

package com.xunan.likou;

import java.math.BigDecimal;
import java.text.DecimalFormat;

public class MedianOfTwoSortedArrays {

    public static void main(String[] args) {
        int[] nums1 = {2};
        int[] nums2 = {};
        double result = findMedianSortedArrays(nums1, nums2);
        System.out.println(result);
        System.out.println(saveRadixPoint(0));
    }

    public static double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int[] medianArray = new int[nums1.length + nums2.length];
        double median = 0.00000;
        if (nums1.length == 0 && nums2.length == 0) {
            return 0.00000;
        } else if (nums2.length == 0) {
            bubbleSort(nums1);
            median = findMedian(nums1);
            return median;
        } else if (nums1.length == 0) {
            bubbleSort(nums2);
            median = findMedian(nums2);
            return median;
        } else {

            for (int i = 0; i < nums1.length; i++) {
                medianArray[i] = nums1[i];
            }
            int j = 0;
            for (int i = nums1.length; i < nums1.length + nums2.length; i++) {
                medianArray[i] = nums2[j];
                j++;
            }
            bubbleSort(medianArray);
            median = findMedian(medianArray);
            return median;
        }
    }

    public static void bubbleSort(int array[]) {
        int temp = 0;
        for (int i = 0; i < array.length - 1; i++) {
            for (int j = 0; j < array.length - 1 - i; j++) {
                if (array[j] > array[j + 1]) {
                    temp = array[j];
                    array[j] = array[j + 1];
                    array[j + 1] = temp;
                }
            }
        }
    }

    public static double saveRadixPoint(double temp) {
        String format = new DecimalFormat("#.00000").format(temp);
        double result = Double.valueOf(format);
        return result;
    }

    public static double findMedian(int array[]) {
        double median = saveRadixPoint(0);
        int length = array.length;
        if ((length % 2) == 1) {
            median = saveRadixPoint(array[length / 2]);
        } else if ((length % 2) == 0) {
            System.out.println("========");
            System.out.println(((array[((length / 2) - 1)] + array[length / 2]) * 0.1) / (2.0 * 0.1));
            median = saveRadixPoint(((array[((length / 2) - 1)] + array[length / 2]) * 0.1) / (2.0 * 0.1));
        }
        return median;
    }

}
